<template>
  <div>
    <van-nav-bar title="账号注册" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="账号："
        placeholder="请输入账号"
        :rules="[
          {
            required: true,
            message: '账号不能为空'
          },
          {
            message: '账号至少包含5个字符',
            pattern: /^\w{5,}$/
          }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码："
        placeholder="密码"
        :rules="[
          {
            required: true,
            message: '密码不能为空'
          },
          {
            message: '密码至少包含5个字符',
            pattern: /^\w{5,}$/
          }
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
    <router-link to="/login" class="link">有账号，去登录~</router-link>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { register } from '@/api/user'

export default {
  name: 'register-page',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      const res = await register(values)
      if (res.status === 200) {
        this.$toast.success('注册成功')
        this.$router.push('/login')
      } else {
        Toast(res.description)
      }
    },
    onClickLeft () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.van-nav-bar {
  background-color: #15b572;
}
/deep/.van-nav-bar .van-icon {
  color: #fff;
}
/deep/.van-nav-bar__title {
  color: #fff;
}
.link {
  display: block;
  color: #666;
  font-size: 14px;
  text-align: center;
}
</style>
